<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\controller\Admin;
use think\Config;
use think\Cache;
use think\Db;
use think\Url;

/**
 * @title 系统模块
 */
class System extends Admin {

    /**
     * @title 留言反馈
     */
    public function feedback() {

        $lists = db('feedback')->order('id desc')->paginate(config('base.page_size'), false, ['query' => request()->get()]);

        $lists2 = [];

        foreach ($lists as $key => $value) {

            $lists2[$key] = $value;

            $smeta = json_decode($value['smeta_json'], true);
            foreach (config('feedback') as $key2 => $field) {
                $lists2[$key][$key2] = $smeta[$key2] ?? '';
            }
        }

        $this->assign('lists', $lists2);
        $this->assign('page', $lists->render());

        return view();
    }

    /**
     * @title 留言批量删除
     * @param type $ids
     */
    public function feedback_deletes($ids) {

        empty($ids) && $this->error('没有选中项');

        $affect_rows = db('feedback')->where('id', 'in', $ids)->delete();
        if ($affect_rows) {
            $this->success('');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * @title 网站静态化
     */
    public function html() {
        $this->assign('category_select', model('article_cat')->lists_select_tree());
        return view();
    }

    /**
     * @title 静态生成首页
     */
    public function html_create_index() {


        $type = input('get.type', 'index');



        if ($type == 'index') {



            Url::root('/html-create.php');
            // 生成首页
            $fileurl = APP_HOST . APP_URL . '/html-create.php';
            $result = file_get_contents($fileurl);
            if ($result) {

                $fileName = APP_DIR . '/index.html';

                $result = str_replace('/html-create.php', '', $result);

                file_put_contents($fileName, $result);


                Url::root('/admin-test.php');
                $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list']);
                ShowMsg("成功创建：index.html，继续进行操作...", $gourl, 0, 1000);
            }
        } elseif ($type == 'list') {

            $id = input('param.id', 0);


            $map['id'] = ['>', $id];

            // 列表索引页面
            $article_cat = db('article_cat')->where($map)->find();

            if (empty($article_cat)) {
                ShowMsg("任务完成", '');
                exit;
            }

            $article_cat_id = $article_cat['id'];
            $alias = $article_cat['alias'];



//            if(empty($alias)){
//                
//                Url::root('/admin-test.php');
//                $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $article_cat_id]);
//                ShowMsg("没有别名：栏目ID  " . $article_cat['id'] . "，跳转下一分类，继续进行操作...", $gourl, 0, 2000);
//                exit;
//            }
            // 分页
            $page = input('get.page', 1);

            Url::root('/html-create.php');
            //$fileurl = APP_HOST . APP_URL . url('index/index/lists', ['id' => $article_cat_id, 'page' => $page]);
            $fileurl = APP_HOST . APP_URL . Url::build('/' . $alias) . '?page=' . $page;


            //
            // Url::root('/admin-test.php');
            // $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $article_cat_id]);
            // ShowMsg($fileurl, $gourl, 0, 2000);
            //
            // exit;





            echo $fileurl;



            try {
                $result = file_get_contents($fileurl);
            } catch (\think\exception\ErrorException $e) {
                //echo $e->getMessage();
                $result = '';
            }

            if ($result) {


                // 如果 达到当前分类的最大页，则跳转到下一篇文章
                if (strpos($result, '<span>' . $page . '</span>') === false) {

                    Url::root('/admin-test.php');
                    $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $article_cat_id, 'page' => 1]);
                    ShowMsg("到达最大页：" . $page . " ， 跳转下一分类：" . $article_cat_id . "，继续进行操作...", $gourl, 0, 500);

                    exit();
                }


                if ($alias && !in_array($alias, ['libs', 'shop', 'static', 'themes', 'ueditor', 'uploads'])) {
                    if (!file_exists(APP_DIR . '/' . $alias)) {
                        //检查是否有该文件夹，如果没有就创建，并给予最高权限
                        mkdir(APP_DIR . '/' . $alias, 0777, true);
                    }


//                    if($page == 1){
//                        $fileName = APP_DIR . '/' . $alias . '/index.html';                       
//                    }else{
//                         $fileName = APP_DIR . '/' . $alias . '/index_'.$page.'.html';
//                    }

                    $fileName = APP_DIR . '/' . $alias . '/index_' . $page . '.html';



                    $result = str_replace('/html-create.php', '', $result);


                    file_put_contents($fileName, $result);

                    if ($page == 1) {
                        file_put_contents(APP_DIR . '/' . $alias . '/index.html', $result);
                    }



                    Url::root('/admin-test.php');
                    $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $id, 'page' => $page + 1]);
                    ShowMsg("成功创建：" . $article_cat_id . " ， page：" . $page . "，继续进行操作...", $gourl, 0, 500);
                } else {

                    Url::root('/admin-test.php');
                    $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $article_cat_id]);
                    ShowMsg("没有别名：" . $article_cat_id . "，跳转下一分类，继续进行操作...", $gourl, 0, 2000);
                }
            } else {
                Url::root('/admin-test.php');
                $gourl = APP_HOST . APP_URL . url('html_create_index', ['type' => 'list', 'id' => $article_cat_id]);
                ShowMsg("没有内容：栏目ID  " . $article_cat['id'] . "，跳转下一分类，继续进行操作...", $gourl, 0, 2000);
            }
        }
    }

    /**
     * @title 静态生成栏目
     */
    public function html_create() {


        $cate = input('param.category', 0);
        $id = input('param.id', 0);

        if ($cate == 0) {
            $catesql = db('article_cat')->column('id');
            $cateid = implode(',', $catesql);
        } else {
            $cateid = db('article_cat')->where('id', $cate)->value('id');
        }

        // $count = db('article')->count();
        $map['cid'] = array('in', $cateid);
        $map['id'] = array('>', $id);

        $article = db('article')->where($map)->find();
        if (empty($article)) {
            ShowMsg("任务完成", '');
            exit;
        }




        $article_id = $article['id'];

        // 如果文章有别名
        $article_alias = $article['alias'];





        // 分类的别名
        $alias = db('article_cat')->where('id', $article['cid'])->value('alias');


        Url::root('/html-create.php');

        if ($article_alias) {

            $fileurl = APP_HOST . APP_URL . Url::build('/' . $article_alias);
        } elseif ($alias && !in_array($alias, ['libs', 'shop', 'static', 'themes', 'ueditor', 'uploads'])) {

            $fileurl = APP_HOST . APP_URL . Url::build('/' . $alias . '/' . $article_id);
        } else {

            Url::root('/admin-test.php');
            $gourl = APP_HOST . APP_URL . url('html_create', ['cate' => $cate, 'id' => $article_id]);
            ShowMsg("ERROR:没有分类&没有别名：" . $article_id . "，继续进行操作...", $gourl, 0, 100);
            exit;
        }


        // $fileurl = url('@index/index/views', ['id' => $val]);    



        try {
            $result = file_get_contents($fileurl);
        } catch (\think\exception\ErrorException $e) {
            //echo $e->getMessage();
            $result = '';
        }





        if ($result) {


            if ($article_alias) {

                if (!file_exists(APP_DIR . '/' . $article_alias)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    @mkdir(APP_DIR . '/' . $article_alias, 0777, true);
                }
                $fileName = APP_DIR . '/' . $article_alias . '/index.html';
            } elseif ($alias && !in_array($alias, ['libs', 'shop', 'static', 'themes', 'ueditor', 'uploads'])) {
                if (!file_exists(APP_DIR . '/' . $alias)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    @mkdir(APP_DIR . '/' . $alias, 0777, true);
                }
                $fileName = APP_DIR . '/' . $alias . '/' . $article_id . '.html';
            }

            $result = str_replace('/html-create.php', '', $result);
            file_put_contents($fileName, $result);

            Url::root('/admin-test.php');
            $gourl = APP_HOST . APP_URL . url('html_create', ['cate' => $cate, 'id' => $article_id]);
            ShowMsg("成功创建：" . $fileurl . "，继续进行操作...", $gourl, 0, 100);
        } else {

            Url::root('/admin-test.php');
            $gourl = APP_HOST . APP_URL . url('html_create', ['cate' => $cate, 'id' => $article_id]);
            ShowMsg("没有内容：" . $article_id . "，继续进行操作...", $gourl, 0, 100);
            exit();
        }
    }

    /**
     * @title 表结构检查 
     */
    public function dbcheck() {

        $db = config('database.database');

        $lists = config('dbcheck');

        if (empty($lists))
            $this->error('表配置文件没找到');

        $tables = Db::query("select table_name from information_schema.tables where table_schema='" . $db . "'");

        $this->assign('lists', $lists);
        $this->assign('tables', $tables);

        return view();
    }

    /**
     * @title 密码修改
     */
    public function password() {
        if (request()->isPost()) {
            $old_password = input('post.old_password');
            $password = input('post.password');
            $repassword = input('post.repassword');

            if ($password != $repassword)
                $this->error('两次输入的密码不一致');

            if ($old_password && $password) {

                $user_array = db('system_user')->where('id', UID)->find();
                if (my_md5($old_password) == $user_array['password']) {
                    if (db('system_user')->where('id', UID)->setField('password', my_md5($password)) !== FALSE) {
                        $this->success("密码修改成功");
                    }
                } else {
                    $this->error('旧密码有误');
                }
            }
        } else {
            return view();
        }
    }

    /**
     * @title 路由
     */
    public function route() {

        $lists = model('system_route')->order('id desc')->paginate(config('base.page_size'), false, ['query' => request()->get()]);

        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());

        return $this->fetch();
    }

    /**
     * @title 路由添加
     */
    public function route_add() {
        if (request()->isPost()) {
            $post = request()->post();

            if ($insert_id = db('system_route')->insertGetId($post)) {
                model('system_route')->route_file_put();
                $this->success('', url('route'));
            } else {
                $this->error('添加失败');
            }
        } else {
            builder('form')
                    ->addItem('full_url', 'input', '原始URL<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('url', 'input', '展示URL<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('type', 'radio', '类型', [1 => '手动', 0 => '自动'])
                    ->build();
            return $this->fetch();
        }
    }

    /**
     * @title 路由编辑
     */
    public function route_edit($id) {

        empty($id) && $this->error('参数不能为空');


        if (request()->isPost()) {
            $post = input('post.');

            if (db('system_route')->where('id', $id)->update($post) !== FALSE) {
                // 更新的文件
                model('system_route')->route_file_put();
                $this->success('', url("route"));
            } else {
                $this->error('修改失败');
            }
        } else {
            $one = db('system_route')->where('id', $id)->find();
            builder('form')
                    ->addItem('full_url', 'input', '原始URL<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('url', 'input', '展示URL<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('type', 'radio', '类型', [1 => '手动', 0 => '自动'])
                    ->build($one);
            return $this->fetch();
        }
    }

    /**
     * @title 路由删除
     */
    public function route_delete($id) {

        empty($id) && $this->error('参数不能为空');

        if (db('system_route')->where('id', $id)->delete() !== FALSE) {
            model('system_route')->route_file_put();
            $this->success('');
        } else {

            $this->error('删除失败');
        }
    }

    /**
     * @title 路由重置
     */
    public function route_reset() {

        if (model('system_route')->route_reset()) {
            $this->success('刷新成功', url('route'));
        } else {
            $this->error('没有任何路由');
        }
    }

    /**
     * @title 菜单
     */
    public function menu() {

        $lists = model('system_menu')->order('listorder asc,id desc')->select();

        // 如果这里不加载额外的数据，在模板输出的时候加载不出来
        foreach ($lists as $key => $value) {
            $lists[$key]['status_text'] = $value->append(['status_text'])->toArray();
        }

        $lists = collection($lists)->toArray();

        // 转成树形
        $tree = new \utils\Tools\Tree($lists);

        $this->assign('lists', $tree->getArray(0));



        builder('list')
                ->addItem('id', '#')
                ->addItem('icon', '图标')
                ->addItem('title', '名称')
                ->addItem('href', '链接')
                ->addItem('status_text', '状态')
                ->addSortItem('listorder', '排序', 'system_menu')
                ->addAction('编辑', 'menu_edit', '<i class="layui-icon layui-icon-edit"></i>', 'layui-btn-normal openbox')
                ->addAction('删除', 'menu_delete', '<i class="layui-icon layui-icon-delete"></i>', 'ajax-get confirm layui-btn-danger')
                ->build();

        return view();
    }

    /**
     * @title 菜单添加
     */
    public function menu_add() {

        if (request()->isPost()) {
            $post = request()->post();


            $insert_id = db('system_menu')->insertGetId($post);

            if (is_numeric($insert_id)) {

                // 更新一下listorder
                db('system_menu')->where('id', $insert_id)->setField('listorder', $insert_id);

                $this->success('', url('menu'));
            } else {
                $this->error('添加失败');
            }
        } else {
            builder('form')
                    ->addItem('pid', 'select', '上级', model('system_menu')->lists_select_tree())
                    ->addItem('title', 'input', '标题<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('icon', 'input', '图标')
                    ->addItem('href', 'input', '链接')
                    ->addItem('status', 'radio', '状态', [1 => '显示', 0 => '隐藏'], 'lay-skin="switch"')
                    ->build(['status' => 1]);
            return view();
        }
    }

    /**
     * @title 菜单编辑
     */
    public function menu_edit($id) {

        empty($id) && $this->error('参数不能为空');

        if (request()->isPost()) {
            $post = request()->post();

            if (db('system_menu')->where('id', $id)->update($post) !== FALSE) {
                $this->success('', url('menu'));
            } else {
                $this->error('添加失败');
            }
        } else {
            $one = db('system_menu')->where('id', $id)->find();
            builder('form')
                    ->addItem('pid', 'select', '上级', model('system_menu')->lists_select_tree(['id' => ['neq', $id]]))
                    ->addItem('title', 'input', '标题<font color="red">*</font>', '', 'lay-verify="required"')
                    ->addItem('icon', 'input', '图标')
                    ->addItem('href', 'input', '链接')
                    ->addItem('status', 'radio', '状态', [0 => '隐藏', 1 => '显示'])
                    ->build($one);
            return view();
        }
    }

    /**
     * @title 菜单删除
     */
    public function menu_delete($id) {
        empty($id) && $this->error('参数不能为空');
        if (db('system_menu')->where('id', $id)->delete() !== FALSE) {
            $this->success('', url('menu'));
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * @title 菜单状态
     */
    public function menu_status() {

        $ids = input('post.ids');
        $value = input('get.value');
        // empty($id) && $this->error('参数不能为空');
        if (db('system_menu')->where('id', 'in', $ids)->setField('status', $value) !== FALSE) {
            $this->success('', url('menu'));
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * @title 导航框架
     */
    public function config_iframe() {
        // 加载内容
        $this->assign('iframe_src', url('admin/system/config'));
        // 加载分类
        $this->assign('nodes', $this->_config_category());
        return $this->fetch('base:iframe');
    }

    /**
     * @title 配置列表
     */
    public function config() {

        $base_dir = APP_DIR . '/../application/extra/';





        if (request()->isPost()) {

            $category = input('post.category');
            $category_root = $base_dir . $category;
            if (is_file($category_root)) {

                $post = input('post.');
                $configs = $post['configs'];

                $title = $post['title'];

                if (empty($title)) {
                    $this->error('配置名称不能为空');
                }

                $array_str = '<?php ' . chr(10) . chr(10) . '/**' . chr(10) . ' * @title ' . $title . '' . chr(10) . ' */' . chr(10) . 'return [' . chr(10);

                foreach ($configs as $key => $value) {
                    if ($value['remark'])
                        $array_str .= chr(9) . "'" . $value['key'] . "' => '" . $value['value'] . "', //" . $value['remark'] . "" . chr(10);
                    else
                        $array_str .= chr(9) . "'" . $value['key'] . "' => '" . $value['value'] . "'," . chr(10);
                }

                $array_str = $array_str . '];';

                /*  【直接保存到文件】  */
                $check = file_put_contents($category_root, $array_str);
                if ($check > 0) {
                    $this->success("保存成功", session('redirect'));
                } else {
                    $this->error("内容为空");
                }
            } else {
                $this->error("请选择一个有效模板文件");
            }
        } else {

            // 维持跳转
            session('redirect', url('config') . '?' . http_build_query(request()->get()));


            /*  【当前的配置文件名称】  */
            $category = input('get.category', 'base.php');
            $this->assign('category', $category);
            /*  【通过当前name获取配置文件的内容】  */
            $config_content = file_get_contents($base_dir . $category);


            // 解析配置
            // preg_match_all("/\'?([^']*)\'? => \'(.*)\',\s*(\/\/[^\r\n]*)?/i", $config_content, $matches);
            //preg_match_all("/(['\"]?)(.*?)\1\s*=>\s*(['\"]?)(.*?)\3,(\/\/)?([^\r\n]*)/i", $config_content, $matches);
            preg_match_all("/\s*[\'\"]?(.*?)[\'\"]?\s*=>\s*[\'\"]?(.*?)[\'\"]?,(\s*\/\/)?([^\r\n]*)/", $config_content, $matches);
            // dd($matches);
            $this->assign('lists', $matches);

            preg_match('/\@title\s*([^\r\n]*)?/i', $config_content, $matches2);
            $title = isset($matches2[1]) ? $matches2[1] : $category;
            $this->assign('title', $title);

            //$lists = parse_config_cnt($content_2);
            $this->assign('config_content', $config_content);
            return $this->fetch();
        }
    }

    public function _config_category() {
        $base_dir = APP_DIR . '/../application/extra/';
        $file_list = my_scan_dir($base_dir . "*.php");
        $navs = array();
        /*  【通过文件名，依次解析title】  */
        foreach ($file_list as $key => $value) {
            $content = file_get_contents($base_dir . $value);
            $array = parse_config_title($content);
            if ($array) {
                $navs[$value] = $array;
            }
        }
        $types = [];
        foreach ($navs as $key => $value) {
            $types[] = [
                'name' => $value,
                'id' => $key,
            ];
        }
        $parent = [
            'id' => '',
            'name' => '所有',
            'spread' => true,
            'children' => $types
        ];
        return json_encode($parent);
    }

}
